/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet.simulacionTrama;

//import ejb.messageBeans.GuardarMensajeBeans;
import ejb.sessionBeans.AvisoFacadeRemote;
import ejb.sessionBeans.EstadoFacadeRemote;
import ejb.sessionBeans.TipoavisoFacadeRemote;
import ejb.sessionBeans.UsuarioFacadeRemote;
import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.jms.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.Aviso;
import modelo.Estado;
import modelo.Tipoaviso;
import modelo.Usuario;

/**
 *
 * @author inftel
 */
@WebServlet(name = "Prueba", urlPatterns = {"/Prueba"})
public class Prueba extends HttpServlet {
    @Resource(mappedName = "jms/Avisos")
    private Queue avisos;
    @Resource(mappedName = "jms/AvisosFactory")
    private ConnectionFactory avisosFactory;

    @EJB
    private EstadoFacadeRemote estadoFacade;
    @EJB
    private TipoavisoFacadeRemote tipoavisoFacade;
    @EJB
    private AvisoFacadeRemote avisoFacade;
    @EJB
    private UsuarioFacadeRemote usuarioFacade;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException, JMSException {


        
        /* List<Tipoaviso> taList=tipoavisoFacade.findAll();
        for(Tipoaviso ta : taList){
        System.out.println(ta.getDescripcion());
        }*/

        //Obtenemso el objeto tipo
        Tipoaviso au = tipoavisoFacade.find(Integer.parseInt(request.getParameter("au")));
        //Obtener latitud y longitud  
        String lt = request.getParameter("lt");
        String ln = request.getParameter("ln");

        //Obtener la fecha
        String fechaString = request.getParameter("ld") + " " + request.getParameter("lh");
        Date date;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

        date = (Date) sdf.parse(fechaString);

        //Obtenemos el objeto usuario de ese telefono
        Usuario usuario = usuarioFacade.findByPhone(request.getParameter("xid"));
        //String xid=request.getParameter("xid");

        Estado estado = estadoFacade.findByDescripcion("Pendiente");




        //Rellenamos el obejto aviso
        Aviso aviso = new Aviso();
       // aviso.setIdAviso(1);
        aviso.setIdUsuario(usuario);
        aviso.setIdTipoaviso(au);
        aviso.setLatitud(lt);
        aviso.setLongitud(ln);
        aviso.setHoraAviso(date);
        aviso.setIdEstado(estado);
        
        
        //Se supone que esto guarda en la BD  
       sendJMSMessageToAvisos(aviso);
       
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (JMSException ex) {
                Logger.getLogger(Prueba.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ParseException ex) {
            Logger.getLogger(Prueba.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (JMSException ex) {
                Logger.getLogger(Prueba.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ParseException ex) {
            Logger.getLogger(Prueba.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private Message createJMSMessageForjmsAvisos(Session session, Object messageData) throws JMSException {
        // TODO create and populate message to send
        Message msg;
        if (messageData instanceof String) {
            TextMessage tm = session.createTextMessage();
            tm.setText(messageData.toString());
            msg = tm;
        } else {
            ObjectMessage om = session.createObjectMessage();
            om.setObject((Serializable) messageData);
            msg = om;
        }
        return msg;
    }

    private void sendJMSMessageToAvisos(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        
        try {
           
            connection = avisosFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(avisos);
            messageProducer.send(createJMSMessageForjmsAvisos(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
        
    }
}
